package com.ruoyi.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.enums.ExceptionStatusEnum;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.project.domain.ProjectCategory;
import com.ruoyi.project.domain.ProjectTemplate;
import com.ruoyi.project.enums.ProjectCategoryEnum;
import com.ruoyi.project.mapper.ProjectCategoryMapper;
import com.ruoyi.project.req.ProjectCategoryReq;
import com.ruoyi.project.service.ProjectCategoryService;
import com.ruoyi.project.service.ProjectTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

@Service
@Slf4j
public class ProjectCategoryServiceImpl extends ServiceImpl<ProjectCategoryMapper, ProjectCategory> implements ProjectCategoryService {

    @Resource
    private ProjectTemplateService projectTemplateService;

    @Override
    @Transactional
    public int add(List<ProjectCategory> projectCategory,Long projectId, String userName, Long deptId, Long userId) {

        //校验是否已经导入
        LambdaQueryWrapper<ProjectCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectCategory::getProjectId, projectId);

        int count = this.count(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ExceptionStatusEnum.PROJECT_CATEGORY_EXIT_ERROR);
        }
        AtomicInteger sort = new AtomicInteger(1);
        projectCategory.forEach(x->{
            //递归保存分类
            saveOrUpdateHandle(x, projectId,null, userName, deptId, userId, sort.get(),true);
            sort.getAndIncrement();

        });

        return 1;
    }

    private void saveOrUpdateHandle(ProjectCategory projectCategory,Long projectId, Long parentId, String userName, Long deptId, Long userId, Integer sort,Boolean isSave) {
        if(isSave){
            projectCategory.setCreateBy(userName);
            projectCategory.setUserId(userId);
            projectCategory.setDeptId(deptId);
            projectCategory.setProjectId(projectId);
        }else{
            projectCategory.setUpdateBy(userName);
            if(Objects.isNull(projectCategory.getId())) {
                projectCategory.setCreateBy(userName);
                projectCategory.setUserId(userId);
                projectCategory.setDeptId(deptId);
                projectCategory.setProjectId(projectId);
            }
        }
        projectCategory.setParentId(parentId);
        projectCategory.setSort(sort);
        log.info("保存分类ProjectCategoryServiceImpl：{}", projectCategory);
        if(projectCategory.getDeleteFlag()){
            this.deleteByIds(projectCategory.getId());
            return;
        }
        this.saveOrUpdate(projectCategory);
        if (!CollectionUtils.isEmpty(projectCategory.getChildren())) {
            int childSort = 1;
            for (ProjectCategory child : projectCategory.getChildren()) {
                saveOrUpdateHandle(child,projectId, projectCategory.getId(), userName, deptId, userId, childSort,isSave);
                childSort++;
            }
        }

    }

    @Override
    @Transactional
    public int updateProjectCategory(List<ProjectCategory> projectCategory,Long projectId, String userName, Long deptId, Long userId, List<Long> ids) {
        AtomicInteger sort= new AtomicInteger(1);
        projectCategory.forEach(x->{
            saveOrUpdateHandle(x,projectId ,null, userName, deptId, userId, sort.get(),false);
            sort.getAndIncrement();

        });
       if(!CollectionUtils.isEmpty(ids)){
            this.removeByIds(ids);
        }
        return 1;
    }


    public void deleteByIds(Long id) {
        ProjectCategory projectCategory = this.getById(id);
        if(Objects.nonNull(projectCategory)){
            if(Objects.equals(ProjectCategoryEnum.GENERATED,projectCategory.getProjectTemplateStatus())){
                throw new BusinessException(ExceptionStatusEnum.PROJECT_CATEGORY_GENERATE_ERROR);
            }
        }
        //校验是否存在子类
        LambdaQueryWrapper<ProjectCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectCategory::getParentId, id);
        int count = this.count(queryWrapper);
        if(count > 0){
            throw new BusinessException(ExceptionStatusEnum.PROJECT_CATEGORY_HAS_CHILD_ERROR);
        }
        this.removeById(id);
    }

    @Override
    public List<ProjectCategory> listAll(ProjectCategoryReq req) {
        //递归获取项目分类信息
        //获取父节点
        LambdaQueryWrapper<ProjectCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.isNull(ProjectCategory::getParentId);
        queryWrapper.eq(ProjectCategory::getProjectId, req.getProjectId());
        List<ProjectCategory> projectCategory1 = this.list(queryWrapper);
        if(CollectionUtils.isEmpty(projectCategory1)){
            return null;
        }
        projectCategory1.forEach(x->{
            x.setSortName(x.getSort()+"");
            getProjectCategory(x);
        });

        return projectCategory1;
    }

    private void getProjectCategory(ProjectCategory projectCategory){
        LambdaQueryWrapper<ProjectCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectCategory::getParentId, projectCategory.getId());
        queryWrapper.orderByAsc(ProjectCategory::getSort);
        List<ProjectCategory> list = this.baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(list)){
            return ;
        }
        list.forEach(x->{
            x.setSortName(projectCategory.getSortName()+"."+x.getSort());
            getProjectCategory(x);
        });
        projectCategory.setChildren(list);
    }

    @Override
    public ProjectTemplate getTree() {

        return projectTemplateService.getTree();
    }
}